Popular Searches
Popular Course Categories
Popular Courses

First Selenium Program

First Selenium Program

Selenium Environment Setup

First Selenium Program

The First Selenium Program is the first practical step toward learning Selenium WebDriver automation. It helps beginners understand how Selenium communicates with a web browser, opens a website, retrieves browser information, performs basic browser operations, and finally closes the browser session.

Selenium is an open-source automation testing tool used for testing web applications across different browsers and platforms. Selenium WebDriver allows automation scripts to control browsers programmatically and is commonly used for functional testing, regression testing, and cross-browser testing.

In this topic, we will create a basic Selenium program using Java and Selenium WebDriver. We will start with a simple browser-launching program and gradually understand WebDriver creation, navigation commands, browser information, WebElement interaction, waits, assertions, TestNG execution, and best practices.

JustAcademy's Selenium Automation Testing course includes Selenium WebDriver, environment setup, first automation scripts, WebElements, TestNG, Page Object Model, cross-browser testing, reporting, and real-time automation projects.


1. What is a Selenium Program?

A Selenium program is a program written in a supported programming language that uses Selenium WebDriver APIs to automate actions in a web browser.

For example, a Selenium program can:

  • Open Google Chrome.
  • Navigate to a website.
  • Find web elements.
  • Enter text into input fields.
  • Click buttons.
  • Select dropdown values.
  • Read text from a webpage.
  • Verify page titles.
  • Verify URLs.
  • Handle browser windows and tabs.
  • Take screenshots.
  • Close the browser.

Basic Selenium Program Flow

Start Program

      ↓

Create WebDriver

      ↓

Launch Browser

      ↓

Open Website

      ↓

Perform Browser Actions

      ↓

Validate Result

      ↓

Close Browser

      ↓

End Program


2. What Will We Build?

Our first Selenium program will perform a simple browser automation task.

Program Requirements

  • Java JDK
  • Java IDE such as IntelliJ IDEA or Eclipse
  • Maven project
  • Selenium WebDriver dependency
  • Google Chrome or another supported browser
  • Internet connection for opening the test website

Our First Automation Task

Launch Chrome

    ↓

Open Google

    ↓

Print Page Title

    ↓

Print Current URL

    ↓

Close Browser


3. Prerequisites

Before creating the first Selenium program, the Java development environment and Selenium project should be configured correctly.

Required Software

Software Purpose
Java JDK Used to compile and execute Java programs.
IDE Used to write, execute, debug, and manage Java code.
Maven Used to manage project dependencies.
Selenium WebDriver Used to automate the browser.
Chrome Browser used for the first automation example.


4. Verify Java Installation

Open the Command Prompt or terminal and execute the following command:

java -version

You can also verify the Java compiler:

javac -version

If Java is installed correctly, the terminal will display the installed Java version.

Example

java version "XX.X.X"

The exact version displayed depends on the Java version installed on the system.


5. Create a Selenium Maven Project

Maven is commonly used to manage Selenium Java project dependencies.

Basic Project Structure

SeleniumFirstProgram

│

├── pom.xml

│

└── src

    └── test

        └── java

            └── FirstSeleniumProgram.java

The pom.xml file contains project configuration and external dependencies.


6. Add Selenium Dependency

Selenium WebDriver can be added to a Maven project through the pom.xml file.

 

   

        org.seleniumhq.selenium

        selenium-java

        4.XX.X

   

 

Use the Selenium version selected for your project or the version approved by your organization.

Why Use a Maven Dependency?

  • Selenium libraries are downloaded automatically.
  • Dependencies are maintained centrally.
  • Project setup becomes easier.
  • Team members can reproduce the project environment.
  • Dependency management becomes simpler.


7. Create the First Java Class

After creating the Maven project and adding Selenium, create a Java class named:

FirstSeleniumProgram.java

The class can initially contain a simple main() method.

Basic Java Structure

public class FirstSeleniumProgram {

 

    public static void main(String[] args) {

 

        // Selenium code will be written here

 

    }

}


8. Import Selenium WebDriver

To use Selenium WebDriver in Java, import the WebDriver interface.

import org.openqa.selenium.WebDriver;

For Chrome automation, import ChromeDriver:

import org.openqa.selenium.chrome.ChromeDriver;

The complete import section becomes:

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;


9. Create WebDriver Object

The WebDriver interface provides methods for controlling a web browser.

A Chrome browser session can be created using:

WebDriver driver = new ChromeDriver();

Understanding the Statement

Part Meaning
WebDriver Selenium interface used to control browsers.
driver Reference variable used to access WebDriver methods.
new Creates a new object.
ChromeDriver() Creates a Chrome browser automation session.

Conceptual Flow

Java Program

     ↓

WebDriver

     ↓

ChromeDriver

     ↓

Google Chrome


10. Complete First Selenium Program

The following is a basic Selenium program that launches Chrome, opens Google, prints the page title and current URL, and closes the browser.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class FirstSeleniumProgram {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

 

            driver.get("https://www.google.com");

 

            System.out.println(

                "Page Title: " + driver.getTitle()

            );

 

            System.out.println(

                "Current URL: " + driver.getCurrentUrl()

            );

 

        } finally {

 

            driver.quit();

        }

    }

}


11. Explanation of the First Selenium Program

Step 1: Import WebDriver

import org.openqa.selenium.WebDriver;

The WebDriver interface provides methods for controlling and interacting with web browsers.

Step 2: Import ChromeDriver

import org.openqa.selenium.chrome.ChromeDriver;

ChromeDriver is used to create and control a Chrome browser session.

Step 3: Create WebDriver

WebDriver driver = new ChromeDriver();

This statement creates a browser automation session.

Step 4: Open Website

driver.get("https://www.google.com");

The get() method navigates the browser to the specified URL.

Step 5: Get Page Title

driver.getTitle();

The getTitle() method returns the title of the current webpage.

Step 6: Get Current URL

driver.getCurrentUrl();

The getCurrentUrl() method returns the URL of the current browser page.

Step 7: Close Browser Session

driver.quit();

The quit() method ends the WebDriver session and closes the browser windows associated with that session.


12. Understanding driver.get()

The get() method is one of the most commonly used WebDriver methods.

Syntax

driver.get("URL");

Example

driver.get("https://www.google.com");

When this statement executes, Selenium instructs the browser to navigate to the specified URL.

Examples

driver.get("https://www.google.com");

 

driver.get("https://www.microsoft.com");

 

driver.get("https://www.selenium.dev");


13. Understanding getTitle()

The getTitle() method retrieves the title of the current webpage.

Syntax

String title = driver.getTitle();

Example

driver.get("https://www.google.com");

 

String title = driver.getTitle();

 

System.out.println("Page Title: " + title);

Possible Output

Page Title: Google

The actual title depends on the webpage being opened.


14. Understanding getCurrentUrl()

The getCurrentUrl() method returns the URL of the page currently loaded in the browser.

Syntax

String url = driver.getCurrentUrl();

Example

driver.get("https://www.google.com");

 

String url = driver.getCurrentUrl();

 

System.out.println("Current URL: " + url);

Possible Output

Current URL: https://www.google.com


15. Understanding driver.quit()

The quit() method terminates the entire WebDriver session.

Example

driver.quit();

It is recommended to close the browser session after the test finishes.

Using finally

try {

 

    driver.get("https://www.google.com");

 

} finally {

 

    driver.quit();

}

Using finally helps ensure that browser cleanup is attempted even when an exception occurs during execution.


16. driver.close() vs driver.quit()

Method Purpose
close() Closes the current browser window.
quit() Ends the WebDriver session and closes associated browser windows.

Example

driver.close();

Use close() when you specifically want to close the current window.

driver.quit();

Use quit() when the complete browser automation session should be terminated.


17. First Program Using Browser Maximization

The browser window can be maximized using the WebDriver window management API.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class BrowserMaximizeDemo {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

 

            driver.manage().window().maximize();

 

            driver.get("https://www.google.com");

 

            System.out.println(

                "Title: " + driver.getTitle()

            );

 

        } finally {

 

            driver.quit();

        }

    }

}


18. First Selenium Program with Browser Navigation

Selenium can navigate between webpages using browser navigation methods.

Navigation Methods

Method Purpose
get() Navigate to a URL.
navigate().to() Navigate to a URL.
navigate().back() Move back in browser history.
navigate().forward() Move forward in browser history.
navigate().refresh() Refresh the current page.

Example

driver.get("https://www.google.com");

 

driver.navigate().to("https://www.microsoft.com");

 

driver.navigate().back();

 

driver.navigate().forward();

 

driver.navigate().refresh();


19. Difference Between get() and navigate().to()

Both get() and navigate().to() can be used to navigate to a URL.

Using get()

driver.get("https://www.google.com");

Using navigate().to()

driver.navigate().to("https://www.google.com");

For simple URL navigation, get() is commonly used in beginner Selenium programs.


20. First Selenium Program with Page Validation

A test program should not only perform actions. It should also validate expected results.

Example

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class PageValidation {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

 

            driver.get("https://www.google.com");

 

            String title = driver.getTitle();

 

            if (title.equals("Google")) {

 

                System.out.println(

                    "Test Passed: Correct page title."

                );

 

            } else {

 

                System.out.println(

                    "Test Failed: Incorrect page title."

                );

            }

 

        } finally {

 

            driver.quit();

        }

    }

}


21. Understanding Assertions

In test automation, assertions are used to compare an actual result with an expected result.

For example:

Expected Title = Google

Actual Title   = Google

If both values match, the validation passes.

TestNG Assertion Example

import org.testng.Assert;

import org.testng.annotations.Test;

 

public class GoogleTitleTest extends BaseTest {

 

    @Test

    public void verifyTitle() {

 

        driver.get("https://www.google.com");

 

        String actualTitle = driver.getTitle();

 

        Assert.assertEquals(

            actualTitle,

            "Google"

        );

    }

}


22. First Selenium Program Using TestNG

After learning the basic Java program, Selenium tests can be executed using TestNG.

Example

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class FirstSeleniumTest {

 

    WebDriver driver;

 

    @BeforeMethod

    public void setUp() {

 

        driver = new ChromeDriver();

    }

 

    @Test

    public void verifyGoogleTitle() {

 

        driver.get("https://www.google.com");

 

        String actualTitle = driver.getTitle();

 

        Assert.assertEquals(

            actualTitle,

            "Google"

        );

    }

 

    @AfterMethod

    public void tearDown() {

 

        if (driver != null) {

            driver.quit();

        }

    }

}


23. Understanding TestNG Annotations

Annotation Purpose
@BeforeMethod Runs before each test method.
@Test Marks a method as a test case.
@AfterMethod Runs after each test method.

Execution Flow

@BeforeMethod

      ↓

Create Browser

      ↓

@Test

      ↓

Open Website

      ↓

Validate Result

      ↓

@AfterMethod

      ↓

Close Browser


24. First Selenium Program to Open a Login Page

A common real-world automation task is opening a login page.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class LoginPageDemo {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

 

            driver.get(

                "https://example.com/login"

            );

 

            System.out.println(

                "Login Page Title: " +

                driver.getTitle()

            );

 

        } finally {

 

            driver.quit();

        }

    }

}

The URL above is an example URL. In a real project, replace it with the URL of the application under test.


25. First Selenium Program with WebElement

After learning browser navigation, the next step is interacting with webpage elements.

Selenium uses the WebElement interface to represent elements such as:

  • Text fields
  • Buttons
  • Links
  • Checkboxes
  • Radio buttons
  • Dropdowns
  • Images
  • Forms

Basic WebElement Example

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class WebElementDemo {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

 

            driver.get("https://example.com");

 

            WebElement heading =

                driver.findElement(By.tagName("h1"));

 

            System.out.println(

                "Heading: " + heading.getText()

            );

 

        } finally {

 

            driver.quit();

        }

    }

}


26. Understanding findElement()

The findElement() method is used to locate a web element on the page.

Syntax

driver.findElement(By.locator);

Example

WebElement element =

    driver.findElement(By.id("username"));

The By class provides different locator strategies.


27. Common Selenium Locators

Locator Example
id By.id("username")
name By.name("username")
className By.className("login-button")
tagName By.tagName("input")
linkText By.linkText("Login")
partialLinkText By.partialLinkText("Log")
cssSelector By.cssSelector("#username")
XPath By.xpath("//input[@id='username']")


28. First Selenium Form Automation

A basic login form might contain username, password, and login button elements.

Example HTML

 

 

Selenium Code

driver.findElement(

    By.id("username")

).sendKeys("testuser");

 

driver.findElement(

    By.id("password")

).sendKeys("password123");

 

driver.findElement(

    By.id("login")

).click();


29. Complete Login Automation Example

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class LoginAutomation {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

 

            driver.get(

                "https://example.com/login"

            );

 

            driver.findElement(

                By.id("username")

            ).sendKeys("testuser");

 

            driver.findElement(

                By.id("password")

            ).sendKeys("password123");

 

            driver.findElement(

                By.id("login")

            ).click();

 

            System.out.println(

                "Login action completed."

            );

 

        } finally {

 

            driver.quit();

        }

    }

}

The locators and URL must be changed according to the actual application under test.


30. Using sendKeys()

The sendKeys() method is used to enter keyboard input into a WebElement.

Example

driver.findElement(

    By.id("username")

).sendKeys("Manish");

It is commonly used with text fields, search boxes, login fields, and form inputs.


31. Using click()

The click() method performs a click action on a clickable WebElement.

Example

driver.findElement(

    By.id("login")

).click();

It can be used with buttons, links, checkboxes, radio buttons, and other clickable elements.


32. Using getText()

The getText() method retrieves visible text from a WebElement.

Example

WebElement heading =

    driver.findElement(

        By.tagName("h1")

    );

 

String text = heading.getText();

 

System.out.println(text);


33. Using isDisplayed()

The isDisplayed() method checks whether an element is displayed on the webpage.

Example

WebElement loginButton =

    driver.findElement(

        By.id("login")

    );

 

if (loginButton.isDisplayed()) {

 

    System.out.println(

        "Login button is displayed."

    );

}


34. Using isEnabled()

The isEnabled() method checks whether an element is enabled for interaction.

Example

WebElement button =

    driver.findElement(

        By.id("login")

    );

 

if (button.isEnabled()) {

 

    System.out.println(

        "Login button is enabled."

    );

}


35. Using isSelected()

The isSelected() method checks whether a selectable element such as a checkbox or radio button is selected.

Example

WebElement checkbox =

    driver.findElement(

        By.id("terms")

    );

 

if (checkbox.isSelected()) {

 

    System.out.println(

        "Checkbox is selected."

    );

}


36. Basic Browser Information Program

The following program demonstrates several useful WebDriver methods.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class BrowserInformation {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

 

            driver.manage().window().maximize();

 

            driver.get("https://www.google.com");

 

            System.out.println(

                "Title: " + driver.getTitle()

            );

 

            System.out.println(

                "URL: " + driver.getCurrentUrl()

            );

 

            System.out.println(

                "Page Source Length: " +

                driver.getPageSource().length()

            );

 

        } finally {

 

            driver.quit();

        }

    }

}


37. First Selenium Program with Explicit Wait

Modern web applications may load elements dynamically. A Selenium script should synchronize with the application instead of relying on unnecessary fixed delays.

Explicit Wait Example

import java.time.Duration;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class ExplicitWaitDemo {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

 

            driver.get("https://example.com");

 

            WebDriverWait wait =

                new WebDriverWait(

                    driver,

                    Duration.ofSeconds(10)

                );

 

            wait.until(

                ExpectedConditions.visibilityOfElementLocated(

                    By.id("username")

                )

            );

 

            System.out.println(

                "Element is available."

            );

 

        } finally {

 

            driver.quit();

        }

    }

}


38. Why Waits Are Important?

Web applications may contain dynamic content, asynchronous requests, animations, delayed rendering, and changing elements. If Selenium attempts to interact with an element before it is ready, the test may fail.

Without Proper Synchronization

Open Page

   ↓

Immediately Find Element

   ↓

Element Not Ready

   ↓

Test Failure

With Explicit Wait

Open Page

   ↓

Wait for Required Condition

   ↓

Element Becomes Available

   ↓

Perform Action

   ↓

Continue Test


39. First Selenium Program with Screenshot

Screenshots are useful for debugging failed automation tests.

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

 

TakesScreenshot screenshot =

    (TakesScreenshot) driver;

 

byte[] image =

    screenshot.getScreenshotAs(

        OutputType.BYTES

    );

In a complete framework, the screenshot can be saved to a file or attached to an automation report.


40. First Selenium Program Using Edge

Selenium WebDriver can also automate Microsoft Edge.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.edge.EdgeDriver;

 

public class EdgeFirstProgram {

 

    public static void main(String[] args) {

 

        WebDriver driver = new EdgeDriver();

 

        try {

 

            driver.get(

                "https://www.microsoft.com"

            );

 

            System.out.println(

                "Title: " + driver.getTitle()

            );

 

        } finally {

 

            driver.quit();

        }

    }

}


41. First Selenium Program Using Firefox

Firefox can also be automated using Selenium WebDriver.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

 

public class FirefoxFirstProgram {

 

    public static void main(String[] args) {

 

        WebDriver driver =

            new FirefoxDriver();

 

        try {

 

            driver.get(

                "https://www.mozilla.org"

            );

 

            System.out.println(

                "Title: " + driver.getTitle()

            );

 

        } finally {

 

            driver.quit();

        }

    }

}


42. Cross-Browser First Program

A reusable first program can allow the tester to choose the browser.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.edge.EdgeDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

 

public class CrossBrowserDemo {

 

    public static void main(String[] args) {

 

        String browser = "chrome";

 

        WebDriver driver;

 

        if (browser.equalsIgnoreCase("chrome")) {

 

            driver = new ChromeDriver();

 

        } else if (browser.equalsIgnoreCase("edge")) {

 

            driver = new EdgeDriver();

 

        } else if (browser.equalsIgnoreCase("firefox")) {

 

            driver = new FirefoxDriver();

 

        } else {

 

            throw new IllegalArgumentException(

                "Unsupported browser: " + browser

            );

        }

 

        try {

 

            driver.get(

                "https://www.google.com"

            );

 

            System.out.println(

                "Browser Title: " +

                driver.getTitle()

            );

 

        } finally {

 

            driver.quit();

        }

    }

}


43. Selenium Manager

Modern Selenium versions include Selenium Manager, which can assist with browser driver management. This can reduce the need for manually downloading and configuring driver executables in many standard environments.

Example

WebDriver driver =

    new ChromeDriver();

The exact behavior depends on the Selenium version, browser installation, operating system, and environment configuration.


44. First Selenium Program Execution Flow

Java Program

      ↓

Create ChromeDriver

      ↓

Start Browser Session

      ↓

Navigate to Website

      ↓

Find WebElements

      ↓

Perform Actions

      ↓

Validate Result

      ↓

Generate Output

      ↓

Quit WebDriver

      ↓

Test Complete


45. Common Errors in First Selenium Program

Error Possible Cause Solution
Cannot resolve Selenium classes Selenium dependency is missing. Check pom.xml and refresh Maven dependencies.
SessionNotCreatedException Browser or driver/environment compatibility problem. Verify browser, Selenium, and environment configuration.
WebDriverException Browser session could not be initialized. Check browser installation and WebDriver configuration.
NoSuchElementException Element could not be located. Verify locator and synchronization.
TimeoutException Expected condition was not satisfied within the timeout. Check locator, page state, and wait strategy.
Browser does not close Cleanup code was not executed. Use appropriate teardown logic and driver.quit().


46. Common Mistakes Beginners Make

  • Forgetting to add Selenium dependency.
  • Using incorrect package imports.
  • Using an incorrect locator.
  • Not waiting for dynamically loaded elements.
  • Using hard-coded sleep statements everywhere.
  • Not closing the browser session.
  • Writing all automation logic in one large class.
  • Hard-coding credentials in source code.
  • Ignoring test validation.
  • Not checking browser compatibility.
  • Using unstable locators.
  • Not maintaining a proper project structure.


47. Best Practices for First Selenium Program

  • Use Maven for dependency management.
  • Keep Selenium version controlled in pom.xml.
  • Use WebDriver interface references.
  • Use meaningful class and method names.
  • Always close the WebDriver session.
  • Use try-finally for cleanup in simple standalone programs.
  • Prefer explicit waits for synchronization requirements.
  • Avoid unnecessary Thread.sleep() calls.
  • Use stable locators.
  • Separate test logic from reusable framework components as the project grows.
  • Use assertions for test validation.
  • Use TestNG or another test framework for structured test execution.


48. Practical Mini Project: Google Search Automation

After learning the basic Selenium program, a beginner can create a small search automation project.

Project Objective

Open Google, enter a search term, submit the search, and validate that the results page loads.

Execution Flow

Start Browser

     ↓

Open Google

     ↓

Locate Search Box

     ↓

Enter Search Text

     ↓

Submit Search

     ↓

Read Page Information

     ↓

Validate Result

     ↓

Close Browser

Example Program

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class GoogleSearchTest {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

 

            driver.get(

                "https://www.google.com"

            );

 

            driver.findElement(

                By.name("q")

            ).sendKeys("Selenium WebDriver");

 

            driver.findElement(

                By.name("q")

            ).submit();

 

            System.out.println(

                "Page Title: " +

                driver.getTitle()

            );

 

            System.out.println(

                "Current URL: " +

                driver.getCurrentUrl()

            );

 

        } finally {

 

            driver.quit();

        }

    }

}


49. Practical Mini Project: Login Automation

A login automation test is one of the most common beginner-level Selenium projects.

Test Scenario

  1. Launch browser.
  2. Open login page.
  3. Locate username field.
  4. Enter username.
  5. Locate password field.
  6. Enter password.
  7. Click login button.
  8. Validate successful login.
  9. Close browser.

Automation Flow

Launch Browser

      ↓

Open Login Page

      ↓

Enter Username

      ↓

Enter Password

      ↓

Click Login

      ↓

Verify Result

      ↓

Close Browser


50. Practical Mini Project: Page Title Validation

Another simple automation task is validating the title of a webpage.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class TitleValidation {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

 

            driver.get(

                "https://www.google.com"

            );

 

            String expectedTitle = "Google";

            String actualTitle = driver.getTitle();

 

            if (actualTitle.equals(expectedTitle)) {

 

                System.out.println(

                    "Test Passed"

                );

 

            } else {

 

                System.out.println(

                    "Test Failed"

                );

 

                System.out.println(

                    "Expected: " +

                    expectedTitle

                );

 

                System.out.println(

                    "Actual: " +

                    actualTitle

                );

            }

 

        } finally {

 

            driver.quit();

        }

    }

}


51. First Selenium Program with Configuration

As automation projects become larger, browser and application settings should be moved into configuration files.

config.properties

browser=chrome

url=https://example.com

headless=false

The automation framework can read these values and create the required browser session.


52. From First Program to Automation Framework

The first Selenium program is the foundation for learning larger automation concepts.

First Selenium Program

        ↓

Browser Automation

        ↓

WebElements

        ↓

Locators

        ↓

Waits

        ↓

Assertions

        ↓

TestNG

        ↓

Page Object Model

        ↓

Data-Driven Testing

        ↓

Reporting

        ↓

Logging

        ↓

Cross-Browser Testing

        ↓

Selenium Grid

        ↓

Git

        ↓

CI/CD

        ↓

Real-Time Automation Framework


53. First Selenium Program - Quick Revision

Concept Purpose
WebDriver Controls and communicates with the browser.
ChromeDriver Creates and controls a Chrome automation session.
driver.get() Opens a URL.
getTitle() Returns the current page title.
getCurrentUrl() Returns the current page URL.
findElement() Locates a web element.
sendKeys() Enters text into an element.
click() Clicks an element.
getText() Retrieves visible element text.
close() Closes the current browser window.
quit() Terminates the WebDriver session.
TestNG Provides structured test execution and validation.
Explicit Wait Waits for a specific condition before continuing.


54. Interview Questions on First Selenium Program

1. What is the first step in a Selenium program?

The first practical step is to create a WebDriver session and launch the required browser.

2. What is WebDriver?

WebDriver is the Selenium API used to control web browsers programmatically.

3. What is ChromeDriver?

ChromeDriver is the Selenium browser driver implementation used to automate Chrome.

4. How do you open a website using Selenium?

driver.get("https://www.google.com");

5. How do you get the title of a webpage?

driver.getTitle();

6. How do you get the current URL?

driver.getCurrentUrl();

7. How do you close the browser?

driver.quit();

8. What is the difference between close() and quit()?

close() closes the current browser window, while quit() terminates the complete WebDriver session and closes associated browser windows.

9. What is findElement()?

findElement() is used to locate a web element using a locator strategy such as ID, name, CSS selector, or XPath.

10. What is sendKeys()?

sendKeys() is used to enter keyboard input into a web element such as a text field.

11. What is click()?

click() performs a click action on a clickable web element.

12. Why are assertions used?

Assertions compare expected and actual results so that the test can determine whether the expected behavior occurred.

13. Why should we use waits?

Waits help synchronize automation with the application when elements or page content are loaded dynamically.

14. Can Selenium automate multiple browsers?

Yes. Selenium WebDriver supports browser automation with browsers such as Chrome, Edge, and Firefox.

15. What should be learned after the first Selenium program?

The next concepts generally include locators, WebElements, browser navigation, waits, alerts, frames, windows, dropdowns, TestNG, Page Object Model, data-driven testing, reporting, and framework development.


55. Learning Outcomes

After completing this topic, learners should be able to:

  • Understand the purpose of a Selenium program.
  • Understand Selenium WebDriver.
  • Create a basic Selenium Maven project.
  • Add Selenium WebDriver dependency.
  • Create a ChromeDriver session.
  • Open a webpage using Selenium.
  • Retrieve page titles.
  • Retrieve current URLs.
  • Navigate between webpages.
  • Find WebElements.
  • Enter text using sendKeys().
  • Click buttons using click().
  • Read text using getText().
  • Perform basic validations.
  • Use TestNG for structured tests.
  • Understand explicit waits.
  • Automate Chrome, Edge, and Firefox.
  • Understand Selenium Manager.
  • Write basic real-world automation programs.
  • Understand the path from a first Selenium script to a complete automation framework.


56. Complete First Selenium Program Workflow

Install Java

      ↓

Create Maven Project

      ↓

Add Selenium Dependency

      ↓

Create Java Class

      ↓

Import WebDriver

      ↓

Create ChromeDriver

      ↓

Launch Browser

      ↓

Open Website

      ↓

Find WebElements

      ↓

Perform Actions

      ↓

Validate Result

      ↓

Print Output

      ↓

Capture Screenshot if Required

      ↓

Quit Browser

      ↓

Test Complete


57. Recommended Selenium Training Resource

JustAcademy's Selenium Automation Testing course covers Selenium WebDriver, environment setup, first automation scripts, WebElements, TestNG, data-driven testing, Page Object Model, cross-browser testing, automation frameworks, reporting, Selenium Grid, CI/CD, and practical automation projects.

JustAcademy Selenium Automation Testing Course

Register for Selenium Course Demo


58. Final Summary

The First Selenium Program introduces the fundamental process of browser automation using Selenium WebDriver. The program starts by creating a WebDriver object, launching the browser, opening a webpage, retrieving browser information, interacting with WebElements, validating results, and finally terminating the browser session.

A simple program such as opening Google and printing its title may look small, but it introduces several important Selenium concepts that form the foundation of professional automation testing.

The basic learning sequence is:

WebDriver

   ↓

Browser Launch

   ↓

Navigation

   ↓

WebElements

   ↓

Locators

   ↓

Actions

   ↓

Waits

   ↓

Assertions

   ↓

TestNG

   ↓

Page Object Model

   ↓

Automation Framework

Once the first Selenium program is understood, learners can progress toward complete automation frameworks involving TestNG, Page Object Model, data-driven testing, reporting, logging, cross-browser execution, Selenium Grid, Git, CI/CD, and real-time automation projects.

Course: Selenium Automation Testing Course

Demo: Register for Course Demo

whatsapp